$( function(){
    let $title = $("#title");
    let $todolist  = $("#todolist");
    let $donelist  = $("#donelist");

    function bindEvent(){
          $title.keydown( function( e = Event){
               
                var code = e.keyCode || e.which ;
                
                if( code === 13 ){
                      createTodo()
                }
          })
           
          $todolist.parent().on("change" , "input[type=checkbox]" , toggleLi );

         
          $todolist.on("click" , "p" , edit)

          
          $todolist.on("blur" , "input[type=text]" , save)

          $todolist.on("click" , "a" , remove)

          count()
    }

    function createTodo(){
          
          let $todo = $(`
          <li>
                <input type="checkbox" >
                <p>${$title.val()}</p>
                <a href="javascript:void(0)">-</a>
          </li>`);
          
          $todolist.prepend($todo);

          $title.val("");
          count()
    }     
    
    
    function toggleLi(){
         
          if( this.checked ){
                $donelist.append( $(this).parent() );
          }else{
                $todolist.append( $(this).parent() );
          }

          count()
    }


    function count(){
      $("span#todocount").text($("ol#todolist").children().length)
      $("span#donecount").text($("ul#donelist").children().length)
  }

   
    function edit(){
         
          if( $(this).children().length > 0 ){
                
                return false;
          }     

          
          var html = $(this).text();
          
          $(this).html(`<input type="text" value=${ html }>`);
         

          $(this).children().select();

    }

   
    function save(){
          
          let value = $(this).val();
          $(this).parent().html( value );
    }

   
    function remove(){
          $(this).parent().remove();
          count()
    }

    bindEvent() 
   
})
